<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="8" :offset="0">
        <el-tree
          :data="data"
          :props="defaultProps"
          default-expand-all
          @node-click="handleNodeClick"
        />
      </el-col>
      <el-col :span="16" :offset="0">
        <div>
          <el-button @click="add()">增加</el-button>
          <el-button @click="upd()">编辑</el-button>
          <el-button>删除</el-button>
          <el-button>导出部门信息</el-button>
        </div>

        <br />

        <h2>部门信息</h2>
        <el-form
          ref="ruleFormRef"
          style="max-width: 300px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="上级部门" width="200px">
            <el-input v-model="ruleForm.pDepartment" disabled />
          </el-form-item>

          <el-form-item label="部门名称" prop="departName">
            <el-input v-model="ruleForm.departName" />
          </el-form-item>

          <el-form-item label="部门编号" prop="departCode">
            <el-input v-model="ruleForm.departCode" />
          </el-form-item>

          <el-form-item label="部门类型" prop="departTypeId">
            <el-select v-model="ruleForm.departTypeId" placeholder="请选择">
              <el-option
                v-for="item in departType"
                :key="item.departTypeId"
                :label="item.departTypeName"
                :value="item.departTypeId"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="部门状态" prop="departState">
            <el-radio-group v-model="ruleForm.departState">
              <el-radio :value="true">使用</el-radio>
              <el-radio :value="false">停用</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="部门级别" prop="departRank">
            <el-input v-model="ruleForm.departRank" />
          </el-form-item>

          <el-form-item label="所在地区" prop="departLocation">
            <el-cascader
              v-model="selectedOptions"
              :options="options"
              @change="handleChange"
            />
          </el-form-item>

          <el-form-item label="负责人" prop="staffId">
            <el-select v-model="ruleForm.staffId" placeholder="请选择">
              <el-option
                v-for="item in staff"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button
              v-if="alter == true"
              type="primary"
              @click="addDepart(ruleFormRef)"
            >
              保存
            </el-button>
            <el-button
              v-if="alter == false"
              type="primary"
              @click="updDepart(ruleFormRef)"
            >
              保存
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>
<script lang="ts" setup>
import { useRouter } from "vue-router";
import axios from "axios";
import { regionData, codeToText } from "element-china-area-data";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";

const router = useRouter();

const alter = ref(true);

//获取点击节点获取到的数据
const departInfo = {
  value: "",
  label: "",
};

//点击节点获取到的数据
const handleNodeClick = (data: any) => {
  //console.log(data.value);
  //console.log(data.label);
  departInfo.value = data.value;
  departInfo.label = data.label;
  //console.log(departInfo.value, departInfo.label);
};

//部门
const data = ref();

const defaultProps = {
  children: "children",
  label: "label",
};

//部门类型
const departType = ref();

//负责人
const staff = ref();

interface RuleForm {
  pId: string;
  pDepartment: string;
  departName: string;
  departCode: string;
  departTypeId: string;
  departState: boolean;
  departRank: string;
  departLocation: string;
  staffId: string;
}

const ruleFormRef = ref<FormInstance>();
//部门添加表单
const ruleForm = reactive<RuleForm>({
  pId: "",
  pDepartment: "",
  departName: "",
  departCode: "",
  departTypeId: "",
  departState: true,
  departRank: "",
  departLocation: "",
  staffId: "",
});
//验证
const rules = reactive<FormRules<RuleForm>>({
  departName: [
    { required: true, message: "请输入部门名称", trigger: "blur" },
    {
      pattern: /^[\u4e00-\u9fa50-9]{0,15}$/,
      message: "只允许输入中文或数字，最多输入15位",
      trigger: "blur",
    },
  ],
  departCode: [
    { required: true, message: "请输入部门编号", trigger: "blur" },
    {
      pattern: /^[0-9]{0,16}$/,
      message: "只允许数字，最多输入16位",
      trigger: "blur",
    },
  ],
  departTypeId: [
    {
      required: true,
      message: "请选择部门类型",
      trigger: "change",
    },
  ],
  departRank: [{ required: true, message: "请输入部门级别", trigger: "blur" }],
  departLocation: [
    {
      required: true,
      message: "请选择所在地区",
      trigger: "change",
    },
  ],
  staffId: [
    {
      required: true,
      message: "请选择负责人",
      trigger: "change",
    },
  ],
});

//获取部门树型
const getDepartment = () => {
  axios.get("Readroute/api/Department/GetDepartmentName?pId=0").then((res) => {
    //console.log(res.data);
    data.value = res.data;
  });
};

//点击增加按钮
const add = () => {
  ruleForm.pId = departInfo.value;
  ruleForm.pDepartment = departInfo.label;
  getStaff();
};

//点击编辑按钮
const upd = () => {
  alter.value = false;
};

//绑定省市区
const options = ref(regionData);
const selectedOptions = ref([]);
const handleChange = () => {
  if (
    selectedOptions.value[0] != null &&
    selectedOptions.value[1] != null &&
    selectedOptions.value[2] != null
  ) {
    const str =
      codeToText[selectedOptions.value[0]] +
      "/" +
      codeToText[selectedOptions.value[1]] +
      "/" +
      codeToText[selectedOptions.value[2]];

    ruleForm.departLocation = str;
  }
};

//获取部门类型
const getDepartType = () => {
  axios.get("Readroute/api/DepartType/GetAllDepartTypes").then((res) => {
    departType.value = res.data;
  });
};

//获取负责人
const getStaff = () => {
  axios
    .get(
      "Readroute/api/StaffInfo/GetStaffNameInfo?departId=" + departInfo.value
    )
    .then((res) => {
      //console.log(res.data);
      staff.value = res.data;
    });
};

//添加
const addDepart = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.post("route/api/Department/AddDepartment", ruleForm).then((res) => {
        if (res.data == 0) {
          ElMessage.error("部门编号或部门名称重复，请重新输入！");
        } else {
          ElMessage.success("保存成功");
          router.push("/src/views/Organization/DepartmentShow.vue");
        }
      });
    } else {
      return;
    }
  });
};

//修改
const updDepart = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};

//重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

onMounted(() => {
  getDepartment();
  getDepartType();
});
</script>
<style>
</style>